# Importing Data
SLOVAKIA <- read_excel("C:/Users/Biniam/Desktop/Documents/Academic/Thesis/Analysis Folder/Excel Files/Oman/Slovakia.xlsx")

# Checking the Imported Data
View(SLOVAKIA)

# Creating Time Series Data
SLOVAKIA_ts <- ts(SLOVAKIA, start=c(2004,02), end=c(2019,06), frequency=12)

# Viewing and Checking the Created Time Series Data
SLOVAKIA_ts
sum(is.na(SLOVAKIA_ts))
library(forecast)
SLOVAKIA_ts <- tsclean(SLOVAKIA_ts)

# Step – 1 of the Box-Jenkins Methodology (Identification: Plotting the Time Series Data)
plot(SLOVAKIA_ts)
plot(aggregate(SLOVAKIA_ts,FUN=mean))

# Decomposing
SLOVAKIA_ts_decomp <- decompose(SLOVAKIA_ts)
plot(SLOVAKIA_ts_decomp)

# Testing for Stationarity
acf(SLOVAKIA_ts, lag.max=20)
pacf(SLOVAKIA_ts, lag.max=20)

# To see any seasonal effect
boxplot(SLOVAKIA_ts~cycle(SLOVAKIA_ts))

# To remove trend effect
SLOVAKIA_ts_diff <- diff(SLOVAKIA_ts)
plot(SLOVAKIA_ts_diff)

# To remove variance effect
SLOVAKIA_ts_log <- log(SLOVAKIA_ts)
plot(SLOVAKIA_ts_log)

# To remove both (Trend and Variance) effects
SLOVAKIA_ts_both <- diff(log(SLOVAKIA_ts))
plot(SLOVAKIA_ts_both)


# Dealing with ACF and PACF
install.packages("tseries")
library(tseries)
acf(SLOVAKIA_ts, lag.max=20)
acf(log(SLOVAKIA_ts), lag.max=20)
acf(diff(SLOVAKIA_ts), lag.max=20)
acf(diff(log(SLOVAKIA_ts)), lag.max=20)
pacf(SLOVAKIA_ts, lag.max=20)
pacf(log(SLOVAKIA_ts), lag.max=20)
pacf(diff(SLOVAKIA_ts), lag.max=20)
pacf(diff(log(SLOVAKIA_ts)), lag.max=20)

# Step-2 of the Box-Jenkins Methodology (Estimating the appropriate model)
SLOVAKIA_ts_model <- auto.arima(SLOVAKIA_ts)
SLOVAKIA_ts_model
SLOVAKIA_ts_model <- auto.arima(SLOVAKIA_ts, ic="aic", trace = TRUE)
SLOVAKIA_ts_model

# Step-3 of the Box-Jenkins Methodology (Diagnosis Checking)
library(tseries)
plot.ts(SLOVAKIA_ts_model$resid)
acf(SLOVAKIA_ts_model$residuals, main='ACF Residual')
pacf(SLOVAKIA_ts_model$residuals, main='ACF Residual')
Box.test(SLOVAKIA_ts_model$resid, lag=20, type="Ljung-Box")

# Forecasting
options(max.print=1000000)
library(forecast)
SLOVAKIA_ts_forecast <- forecast (SLOVAKIA_ts_model, level=c(95), h=258)
plot(SLOVAKIA_ts_forecast)
SLOVAKIA_ts_forecast             


write.table(SLOVAKIA_ts_forecast, file="Slovakia_TSA.csv", sep=",")
